// 第一步，引入vue和vuex
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

// 第二步，创建一个store
let store = new Vuex.Store({
  state: {
    // 存放数据
    carPanelData: [],
    // 是否为最大值
    maxOff: false,
    // 控制显示隐藏
    carShow: false,
    ball: {
      show: false, // 显示与隐藏
      el: null, // 点击哪一个
      img: ''
    }
  },
  getters: {
    // 计算
    // 数量
    totalCount (state) {
      let count = 0
      state.carPanelData.forEach(goods => {
        count += goods.count
      })
      return count
    },
    // 价格
    totalPrice (state) {
      let price = 0
      state.carPanelData.forEach(goods => {
        price += goods.count * goods.price
      })
      return price
    }
  },
  mutations: {
    addCarPanelData (state, data) {
      let bOff = true // 判断购物车是否添加过
      state.carPanelData.forEach(goods => {
        if (goods.sku_id === data.sku_id) {
          goods.count++
          if (goods.count > goods.limit_num) {
            goods.count--
            state.maxOff = true
            bOff = false
            return
          }
          bOff = false
          state.carShow = true
          state.ball.show = true
          state.ball.img = data.ali_image
          state.ball.el = event.path[0]
        }
      })
      if (bOff) {
        let goodsData = data
        Vue.set(goodsData, 'count', 1)
        state.carPanelData.push(goodsData)
        state.carShow = true
        state.carShow = true
        state.ball.show = true
        state.ball.img = data.ali_image
        state.ball.el = event.path[0]
      }
      // console.log(state.carPanelData)
    },
    closePrompt (state) { // 关闭提示
      state.maxOff = false
    },
    delCarPanelData (state, id) { // 删除购物车商品
      state.carPanelData.forEach((goods, index) => {
        if (goods.sku_id === id) {
          state.carPanelData.splice(index, 1)
          return false
        }
      })
    },
    showCar (state) { // 显示购物车
      state.carShow = true
    },
    hideCar (state) { // 隐藏购物车
      setTimeout(() => {
        state.carShow = false
      }, 500)
    }
  }
})

// 第三步，将store暴露
export default store

